<template>
  <div class="rb-tag-list">
    <template v-for="(item, index) in list" :key="index">
      <rb-tag
        v-if="index < max - 1"
        :isActive="myValue == item.value || myValue?.includes(item.value)"
        @click="handleChange(item, index)"
        >{{ item.label }}</rb-tag
      >
    </template>
    <rb-tag v-if="list.length > max - 1" style="color: var(--primary-color)">
      更多
    </rb-tag>
  </div>
</template>

<script setup>
const emit = defineEmits(["update:modelValue", "onSelect"]);
const props = defineProps({
  list: {
    type: Array,
    default: [],
  },
  modelValue: {
    default: undefined,
  },
  multiple: {
    default: false,
  },
  max: {
    type: Number,
    default: 8,
  },
});
const myValue = ref([]);
watch(
  () => props.modelValue,
  (newVal, oldVal) => {
    if (props.multiple) {
      if (!newVal) {
        myValue.value = [];
        return;
      }
    }
    myValue.value = newVal;
  },
  {
    immediate: true,
  }
);
const handleChange = (item, index) => {
  if (props.multiple) {
    const index = myValue.value.indexOf(item.value);
    console.log('index',index,item.value)
    if (index > -1) {
      myValue.value.splice(index, 1);
    } else {
      myValue.value.push(item.value);
    }
  } else {
    if (item.value === myValue.value) {
      myValue.value = undefined;
    } else {
      myValue.value = item.value;
    }
  }
  emit("update:modelValue", myValue.value);
  emit("onSelect", { current: item.value, value: myValue.value });
};
</script>

<style lang='scss' scoped>
.rb-tag-list {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
  gap: 16px;
}
</style>